package cn.cvs.web;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysRoleService;
import cn.cvs.service.SysUserService;
import cn.cvs.util.Constants;
import cn.cvs.util.DataTransfer;
import cn.cvs.util.PageSupport;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SysUserController {

    @Resource
    SysUserService sysUserService;

    @Resource
    SysRoleService sysRoleService;

    //跳转到登录页面
   @RequestMapping(value = {"/toLogin","/"})
    public String toLogin(){
       return "login";
   }


   //登录
   @RequestMapping("/login")
   public String doLogin(@RequestParam String account, @RequestParam String password, HttpSession session,Model model){
       SysUser sysUser = sysUserService.queryUser(account, password);
       if (sysUser!=null){
           session.setAttribute(Constants.USER_SESSION,sysUser);
           return "frame";
       }else {
           model.addAttribute("error","用户名或密码错误");
           return "login";
       }
   }

   //跳转到主页面
    @RequestMapping("/sys/toMain")
    public String toMain(){
       return "frame";
    }

    //注销登录
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        Object user = session.getAttribute(Constants.USER_SESSION);
        if (user!=null){
            session.removeAttribute(Constants.USER_SESSION);
        }
        //转发到某个请求
        return "forward:/toLogin";
        //重定向到某个请求
        //return "redirect:/**"
    }

   //局部异常处理
    //只会处理当前控制器抛出的异常
    @ExceptionHandler(value = {Exception.class})
    public String exceptionHandle(Exception e,Model model){
       e.printStackTrace();
       model.addAttribute("exception",e);
       return "sysError";
    }
    //根据输入算输出
    //输入：入参（页面传给后台控制器的参数）
    //输出：出参（后台传给页面的参数）
    //对于前后台不分离的系统（使用jsp...）
    //指的就是放入作用域中的数据，就是页面el表达式中的变量
    //用户列表\
    @RequestMapping("/sys/user/list")
    public String list(@RequestParam(value = "queryRealName",required = false) String realName,@RequestParam(value = "queryRoleId",required = false) Integer roleId,@RequestParam(value = "pageIndex",required = false,defaultValue = "1") Integer pageNo,Model model){
        //出参 queryRealName
        model.addAttribute("queryRealName",realName);
        //出参 queryRoleId
        model.addAttribute("queryRoleId",roleId);
        // 出参 roleList 角色类表(全部的角色)
        List<SysRole> sysRoles = sysRoleService.queryAllRoles();
        model.addAttribute("roleList",sysRoles);
        //出参 userList  用户列表
        List<SysUser> sysUsers
                = sysUserService.queryUsers(realName, roleId, pageNo, Constants.pageSize);
        model.addAttribute("userList",sysUsers);
        //totalCount (参与条件分页)总记录数
        int count = sysUserService.queryCount(realName, roleId);
        model.addAttribute("totalCount",count);
        //currentPageNo 当前页码 就是入参 pageIndex
        model.addAttribute("currentPageNo",pageNo);
        //totalPageCount 总页数
        PageSupport pageSupport = new PageSupport();
        //设置pageSize 一页几条记录
        pageSupport.setPageSize(Constants.pageSize);
        //设置参与分页的总记录数
        pageSupport.setTotalCount(count);
        //获得总页数
        int totalPageCount = pageSupport.getTotalPageCount();
        model.addAttribute("totalPageCount",totalPageCount);
        return "sysUser/list";
    }
    //跳转到添加用户页面
    @RequestMapping("/sys/user/toAdd")
    public String toAddUser(Model model){
        List<SysRole> sysRoles = sysRoleService.queryAllRoles();
        model.addAttribute("sysRoles",sysRoles);
        return "sysUser/add";
    }

    /**
     *
     * @param sysUser
     * @param bindingResult
     * @param session
     * @param model
     * @return
     */
    //添加用户
//    @PostMapping("/sys/user/add")
//    public String addUser(@Valid SysUser sysUser, BindingResult bindingResult, HttpSession session,
//                          HttpServletRequest request, Model model,
//                          @RequestParam(value = "idPic",required = false) MultipartFile idPic){
//        //System.out.println(sysUser);
//        //验证是否登录
//        SysUser loginUser = (SysUser)session.getAttribute(Constants.USER_SESSION);
//        if (loginUser==null){
//            //还没有登录
//            model.addAttribute("error","请登录后操作");
//            return "forward:/toLogin";
//        }
//        //查看后台验证的结果
//        if (bindingResult.hasErrors()){
//            //后台验证错误
//            throw new RuntimeException("后台数据校粘错误");
//        }
//        //保存图片
//        //idPic.transferTo(new File("xxx"));
//        //图片命名规则
//        //时间戳_原名
//        //创建上传文件的新名字
//        String saveFileName=System.currentTimeMillis()+"_"+idPic.getOriginalFilename();
//        //服务器的保存位置
//        // /工程目录/statics/uploadFiles/
//        // 工程目录 是指该工程在服务器上的具体位置
//        // D:/web_server/tomcat9/webapps/ssmdeno-kf01/
//        //D:/web_server/tomcat9/webapps/ssmdeno-kf01/statics/uploadFiles/
//        String realPath = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadFiles");
//        //创建保存的目录
//        File file = new File(realPath);
//        if (!file.exists()){
//            file.mkdirs();
//        }
//        //创建要保存到服务器上的文件
//        File saveFile = new File(file, saveFileName);
//        //保存文件
//        try {
//            idPic.transferTo(saveFile);
//        } catch (IOException e) {
//            e.printStackTrace();
//            throw new RuntimeException("保存图片失败"+e);
//        }
//        //创建保存到数据库的图片路径信息
//        String idPicPath=File.separator+"statics"+File.separator+"uploadFiles"+File.separator+saveFileName;
//        sysUser.setIdPicPath(idPicPath);
//        sysUser.setCreatedTime(new Date());
//        sysUser.setCreatedUserId(loginUser.getId());
//        int i = sysUserService.addUser(sysUser);
//        if (i>0){
//            return "redirect:/sys/user/list";
//        }else {
//            throw  new RuntimeException("添加用户失败，请重试");
//        }
//
//    }
    @PostMapping("/sys/user/add")
    public String addUser(@Valid SysUser sysUser, BindingResult bindingResult, HttpSession session,
                          HttpServletRequest request, Model model,
                          @RequestParam(value = "attaches",required = false) MultipartFile[] attaches){
        //System.out.println(sysUser);
        //验证是否登录
        SysUser loginUser = (SysUser)session.getAttribute(Constants.USER_SESSION);
        if (loginUser==null){
            //还没有登录
            model.addAttribute("error","请登录后操作");
            return "forward:/toLogin";
        }
        //查看后台验证的结果
        if (bindingResult.hasErrors()){
            //后台验证错误
            throw new RuntimeException("后台数据校粘错误");
        }
        for (int i=0;i<attaches.length;i++){
            //保存图片
            //idPic.transferTo(new File("xxx"));
            //图片命名规则
            //时间戳_原名
            //创建上传文件的新名字
            String saveFileName=System.currentTimeMillis()+"_"+attaches[i].getOriginalFilename();
            //服务器的保存位置
            // /工程目录/statics/uploadFiles/
            // 工程目录 是指该工程在服务器上的具体位置
            // D:/web_server/tomcat9/webapps/ssmdeno-kf01/
            //D:/web_server/tomcat9/webapps/ssmdeno-kf01/statics/uploadFiles/
            String realPath = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadFiles");
            //创建保存的目录
            File file = new File(realPath);
            if (!file.exists()){
                file.mkdirs();
            }
            //创建要保存到服务器上的文件
            File saveFile = new File(file, saveFileName);
            //保存文件
            try {
                attaches[i].transferTo(saveFile);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("保存图片失败"+e);
            }
            //创建保存到数据库的图片路径信息
            String path=File.separator+"statics"+File.separator+"uploadFiles"+File.separator+saveFileName;
            if (i==0){
                sysUser.setIdPicPath(path);
            }else{
                sysUser.setWorkPicPath(path);
            }
        }
        sysUser.setCreatedTime(new Date());
        sysUser.setCreatedUserId(loginUser.getId());
        int i = sysUserService.addUser(sysUser);
        if (i>0){
            return "redirect:/sys/user/list";
        }else {
            throw  new RuntimeException("添加用户失败，请重试");
        }

    }
    @RequestMapping("/sys/user/toUpdate")
    public String toUpdateUser(@RequestParam (value = "uid") Integer id,Model model){
        SysUser sysUser = sysUserService.queryById(id);
        model.addAttribute("sysUser",sysUser);
        //查询出所有角色
        List<SysRole> sysRoles = sysRoleService.queryAllRoles();
        model.addAttribute("sysRoles",sysRoles);
        return "sysUser/update";
    }
    @PostMapping("/sys/user/update")
    public String updUser(SysUser sysUser,HttpSession session,Model model){
        SysUser attribute = (SysUser)session.getAttribute(Constants.USER_SESSION);
        if (attribute==null){
            model.addAttribute("error","请登录后操作");
            return "forward:/toLogin";
        }
        sysUser.setUpdatedTime(new Date());
        sysUser.setUpdatedUserId(attribute.getId());
        int i = sysUserService.updateUser(sysUser);
        if (i>0){
            return "redirect:/sys/user/list";
        }else{
            throw new RuntimeException("修改失败，请重试");
        }
    }
    //同步查看用户信息
    @GetMapping("/sys/user/view/{uid}")
    public String viewUser(@PathVariable("uid") Integer id,Model model){
       //根据id查询用户对象
        SysUser sysUser = sysUserService.queryById(id);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/view";
    }
    //验证account是否唯一
    @ResponseBody//标识这个方法是处理异步请求，返回结果不走视图解析器
    @GetMapping("/sys/user/userExist")
    public Object userExists(@RequestParam String account){
        //定义一个返回结果
        Map<String,Object> resultMap=new HashMap<>();
        if (StringUtils.isEmpty(account)){
            resultMap.put("exist","-1");
            resultMap.put("msg","account is blank");
            return JSON.toJSONString(resultMap);
        }
        try {
            int count = sysUserService.queryUserCount(account);
            if (count==1){
                //不可
                resultMap.put("exist","1");
            }else{
                //0 可
                resultMap.put("exist","0");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("exist","-1");
            resultMap.put("msg",e.getMessage());
        }
        return JSON.toJSONString(resultMap);
    }

    //异步查看用户信息
    @ResponseBody
    @GetMapping("/sys/user/{uid}/view")
    public Object asyViewUser(@PathVariable("uid") Integer id){
        //返回对象
        DataTransfer<SysUser> dto=new DataTransfer<>();
        try {
            SysUser sysUser = sysUserService.queryById(id);
            if (sysUser==null){
                dto.setStatus("nodata");
                return JSON.toJSONString(dto);
            }
            dto.setStatus("ok");
            dto.setData(sysUser);
            return JSON.toJSONString(dto);
        } catch (Exception e) {
            e.printStackTrace();
            dto.setStatus("failed");
            return JSON.toJSONString(dto);
        }
    }
    //异步删除用户
    @ResponseBody
    @DeleteMapping("/sys/user/{uid}")
    public Object deleteUser(@PathVariable("uid")Integer id,HttpSession session,HttpServletRequest request){
        //返回对象
        Map<String,Object> resultMap=new HashMap<>();
        SysUser loginUser=(SysUser) session.getAttribute(Constants.USER_SESSION);
        //判断是否登录
        if (loginUser==null){
            resultMap.put("delResult","noLogin");
            resultMap.put("msg","请登录后在操作");
            return JSON.toJSONString(resultMap);
        }
        //是否是管理员
        if (loginUser.getRoleId()!=1){
            resultMap.put("delResult","notAdmin");
            resultMap.put("msg","非管理员不能删除用户");
            return JSON.toJSONString(resultMap);
        }
        //删除的用户不能是管理员
        SysUser sysUser = sysUserService.queryById(id);
        if (sysUser==null){
            resultMap.put("delResult","notexist");
            return JSON.toJSONString(resultMap);
        }
        if (sysUser.getRoleId()==1){
            //删除的是一个管理员
            resultMap.put("delResult","delAdmin");
            resultMap.put("msg","不能删除管理员");
            return JSON.toJSONString(resultMap);
        }
        //执行删除操作
        int i = sysUserService.deleteUser(id, request);
        if (i>0){
            //删除成功
            resultMap.put("delResult","true");
        }else{
            //删除失败
            resultMap.put("delResult","false");
        }
        return JSON.toJSONString(resultMap);
    }

}
